package com.pig4cloud.pig.ads.controller;
import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSONObject;
import com.pig4cloud.pig.ads.utils.OkHttpUtil;
import com.pig4cloud.pig.ads.utils.RSAUtils;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
 * @projectName:pig
 * @description:
 * @author:Mr.Chen
 * @createTime:2020/11/23 20:15
 * @version:1.0 /admin/home/doHomePage
 */

@Controller
@RequestMapping("/home")
@Api(value = "home", tags = "运营平台授权登录")
public class HomeController {

	/**
	 * 通过客户端方式获取token，无法与用户绑定
	 */
	private final static String HTTP_TOKEN_URL = "auth/oauth/token?grant_type=client_credentials&scope=server";

	/**
	 * 通过用户名和密码的方式获取token，三方平台对用户名和密码做加密
	 */
	private final static String HTTP_PASSWORD_TOKEN_URL = "auth/oauth/token";
	/**
	 * 投放平台首页
	 */
	private final static String HTTP_HOME_URL = "#/wel/index";

	//@Autowired
	//UserDetailsService userDetailsService;


	/*public static void main(String[] args) throws UnsupportedEncodingException {
		String mgrapi = Base64.encode("mgr-api:mgr-api");
		System.out.println(mgrapi);

		byte[] decoded = Base64.decode("bWdyLWFwaTptZ3ItYXBp");
		String token = new String(decoded, CharsetUtil.UTF_8);
		System.out.println(token);

	}*/


	/**
	 * 进入投放系统
	 * @param rsaNameKey 加密后的用户名
	 * @param rsaPwdKey 加密后的密码
	 * mgr-api
	 */

	@GetMapping("/doHomePage")
	public void doHomePage(String rsaNameKey,String rsaPwdKey,HttpServletRequest request, HttpServletResponse response) throws IOException {
		//mgr-api
		String token="";
		String authorization="Basic "+Base64.encode("mgr-api:mgr-api");
		StringBuffer url = request.getRequestURL();
		String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(request.getSession().getServletContext().getContextPath()).append("/").toString();
		if (StringUtils.isNotBlank(rsaNameKey)&&StringUtils.isNotBlank(rsaPwdKey)) {
			String userName = RSAUtils.getKey(rsaNameKey.replace(" ","+"));
			String password = RSAUtils.getKey(rsaPwdKey.replace(" ","+"));
			if (StringUtils.isNotBlank(userName)&&StringUtils.isNotBlank(password)) {
				//UserDetails user = userDetailsService.loadUserByUsername(userName);
				//验证用户是否存在
				//if (user != null) {
					//获取当前域名  http://192.168.0.45:9999/
					String result =OkHttpUtil.getRequestForGetHeader(tempContextUrl+HTTP_PASSWORD_TOKEN_URL + "?username=" + userName + "&password=" + password + "&grant_type=password&scope=server&aes_state=1", authorization);
					if (StringUtils.isNotBlank(result)) {
						JSONObject jsonObject = JSONObject.parseObject(result);
						if (jsonObject != null) {
							token = jsonObject.getString("access_token");
							/*if(StringUtils.isNotBlank(token)){
								//设置请求Header
								response.setHeader("Authorization","Basic "+token);
							}*/
						}
					}
				//}
			}
		}
		//跳转投放平台首页
		//response.sendRedirect(HTTP_HOME_URL);
		sendByPost(response,tempContextUrl+"/#/wel/index",token);
	}


	/**
	 * 跳转到投放平台首页，添加header
	 * @param response
	 * @param url
	 * @param token
	 * @throws IOException
	 */
	public void sendByPost(HttpServletResponse response,String url,String token) throws IOException
	{
		response.setContentType("text/html");
		//请求token
		response.setHeader("Authorization","Basic "+token);
		//添加cookie到页面中
		Cookie authorization = new Cookie("Authorization","Basic "+token);
		response.addCookie(authorization);
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println(" <HEAD><TITLE>sender</TITLE></HEAD>");
		out.println(" <meta name=\"\" content=\"Basic "+token+"\">");
		out.println(" <BODY>");
		out.println("<form name=\"submitForm\" action=\""+url+"\" method=\"get\">");
		out.println("</from>");
		out.println("<script>window.document.submitForm.submit();</script> ");
		out.println(" </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}
}
